package com.zjlanyun.erp;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.aihook.pulltorefresh.lib.XListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.zjlanyun.erp.adapter.AddressBookAdapter;
import com.zjlanyun.erp.model.AddressBookModel;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.utils.Toastor;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;

import cz.msebera.android.httpclient.Header;

public class MainAddressBook extends Fragment implements XListView.IXListViewListener {

	private View rootView;
	private XListView list;
	private ArrayList<AddressBookModel> mList;
	private AddressBookAdapter mAdapter;
	private int[] bgcolor = { R.drawable.bg_circle_1, R.drawable.bg_circle_2, R.drawable.bg_circle_3,
			R.drawable.bg_circle_4, R.drawable.bg_circle_5, R.drawable.bg_circle_6, R.drawable.bg_circle_7,
			R.drawable.bg_circle_8, R.drawable.bg_circle_9, R.drawable.bg_circle_10, R.drawable.bg_circle_11 };
	private HashMap<String, Object> userinfo;
	private int page = 0; //页码
	private Toastor toastor;
	private String serverUrl = "";
	private Handler mHandler;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (rootView == null) {
			rootView = LayoutInflater.from(getActivity()).inflate(R.layout.main_address_book, null);
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView();
		getData();
	}

	// 初始化View
	@SuppressLint("NewApi")
	private void initView() {
		list = (XListView) rootView.findViewById(R.id.list);
		
		userinfo = Common.getUserinfo(getActivity());
		toastor = new Toastor();
		serverUrl = WebApi.addressbook(getActivity());
		mHandler = new Handler();
		
		list.setOverScrollMode(View.OVER_SCROLL_NEVER);
		list.setPullLoadEnable(true);
		list.setRefreshTime("刚刚");
		list.setXListViewListener(this);
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(getActivity(), MainAddressBookDetail.class);
				intent.putExtra("FItemID", mList.get(position-1).getFItemID());
				startActivity(intent);
			}
		});
	}
	
	// 初始化数据
	private void getData(){
		page++;
		if(page == 1){
			mList = new ArrayList<AddressBookModel>();
			mAdapter = new AddressBookAdapter(getActivity(), mList, bgcolor);
			list.setAdapter(mAdapter);
		}
		
		if((Boolean) userinfo.get("isDemo")){
			for (int i = 1; i < 12; i++) {
				int n = (int) (Math.random() * 10);
				AddressBookModel model = new AddressBookModel();
				model.setFItemID(i);
				model.setFName("李张" + i);
				model.setSurname("张" + i);
				model.setFMobilePhone("1395416554" + n);
				model.setNamebgid(n); // 根据手机末尾数设置颜色编号
				mList.add(model);
			}
			mAdapter.notifyDataSetChanged();
		}else{
			AsyncHttpClient client = new AsyncHttpClient();
			RequestParams params = new RequestParams();
			params.put("username", userinfo.get("username"));
			params.put("password", userinfo.get("password"));
			params.put("type", "list");
			params.put("page", page);
			client.post(serverUrl, params, new TextHttpResponseHandler() {
				@Override
				public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
					toastor.showShortToast(Data.SERVER_URL_ERROR);
				}

				@Override
				public void onSuccess(int statusCode, Header[] headers, String responseString) {
					JSONTokener jsonParser = new JSONTokener(responseString);
					try {
						JSONObject json = (JSONObject) jsonParser.nextValue();
						if(json.getInt("code") == 0){
							JSONObject data = json.getJSONObject("data");
							JSONArray Table1 = data.getJSONArray("Table1");
							for(int i = 0; i < Table1.length(); i++){
								int n = (int) (Math.random() * 10);
								JSONObject item = Table1.getJSONObject(i);
								AddressBookModel model = new AddressBookModel();
								model.setFItemID(item.getInt("FItemID"));
								model.setFName(item.getString("FName"));
								model.setFMobilePhone(item.getString("FMobilePhone"));
								model.setNamebgid(n);
								if(!item.getString("FName").equals("")){
									model.setSurname(item.getString("FName").substring(0, 1));
								}
								mList.add(model);
							}
							JSONArray Table = data.getJSONArray("Table");
							JSONObject TableItem = Table.getJSONObject(0);
							if(page >= TableItem.getInt("PageCount")){
								list.setPullLoadEnable(false);
							}
							mAdapter.notifyDataSetChanged();
						}else{
							toastor.showShortToast(json.getString("message"));
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			});
		}
		stopLoad();
	}
	
	private void stopLoad(){
		list.stopRefresh();
		list.stopLoadMore();
		list.setRefreshTime("");
	}

	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				page = 0;
				list.setPullLoadEnable(true);
				getData();
			}
		}, 1200);
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				getData();
			}
		}, 500);
	}
	
	
}
